package com.ndood.agent.core.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ndood.core.properties.CommonConstants;
import com.ndood.core.properties.SecurityProperties;
import com.ndood.core.support.SimpleResponse;

/**
 * 退出登录成功处理器，将日志插入数据库
 */
@Component("agentLogoutSuccessHandler")
public class AgentLogoutSuccessHandler implements LogoutSuccessHandler{
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SecurityProperties securityProperties;
	
	private ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * 退出登录成功处理
	 */
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		logger.info("退出成功!");
		if(StringUtils.isBlank(securityProperties.getBrowser().getSignOutSuccessUrl())){
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(CommonConstants.SUCCESS, "退出成功")));
			response.getWriter().flush();
		} else {
			response.sendRedirect(securityProperties.getBrowser().getSignOutSuccessUrl());
		}
	}
	
}